﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
using EquipmentConfig.Class;
using System.Threading;

namespace EquipmentConfig
{
    public partial class FlowWeirGroove : Form
    {
        private MainForm mf;
        private int dType;
        private int dIndex;

        public FlowWeirGroove(MainForm mainForm, int debugType, int index)
        {
            InitializeComponent();
            mf = mainForm;
            dType = debugType;
            dIndex = index;
            this.Text = string.Format("流量堰槽{0}设置", index);
        }

        /// <summary>
        ///检查流量堰槽数据
        /// </summary>
        /// <returns>true,false</returns>
        private bool CheckFlowData(ref List<byte> listData)
        {
            try
            {
                if (dgvYc.Rows.Count == 0)
                {
                    Messages.ShowAlertDialog("流量堰槽数据为空，请先读取或导入!", false);
                    return false;
                }

                for (int i = 0; i < mf.flowData.Length; i++)
                {
                    DataGridViewCell dc = dgvYc.Rows[i % 43].Cells[(i / 43) * 2 + 1];
                    if (dc.Value == null)
                    {
                        dc.Selected = true;
                        Messages.ShowAlertDialog("截面积不能为空!", false);
                        return false;
                    }

                    if (!Common.CheckIsNum(dc.Value.ToString()))
                    {
                        dc.Selected = true;
                        Messages.ShowAlertDialog("截面积必须为数字!", false);
                        return false;
                    }

                    double dbValue = Convert.ToDouble(dc.Value);
                    if (dbValue > 42949.67295)
                    {
                        dc.Selected = true;
                        Messages.ShowAlertDialog("截面积最大不能超过42949.67295!", false);
                        return false;
                    }

                    if (i > 0 && i < 43)
                    {
                        if (dbValue <= Convert.ToDouble(dgvYc.Rows[i % 43 - 1].Cells[(i / 43) * 2 + 1].Value))
                        {
                            dc.Selected = true;
                            Messages.ShowAlertDialog("截面积必须增大!", false);
                            return false;
                        }
                    }

                    listData.AddRange(BitConverter.GetBytes(Convert.ToInt32(dbValue * 100000)));
                }
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 获取流量堰槽数据
        /// </summary>
        /// <param name="byteData">流量堰槽数据字节数组</param>
        /// <returns>true,false</returns>
        private double[] GetFlowData(byte[] byteData)
        {
            double[] dblData = new double[256];
            if (byteData.Length != 1024)
            {
                return dblData;
            }

            for (int i = 0; i < mf.flowData.Length; i++)
            {
                dblData[i] = BitConverter.ToInt32(byteData, i * 4) / 100000.0;
            }
            return dblData;
        }

        /// <summary>
        /// 流量堰槽设置读取
        /// </summary>
        private void btnReadYc_Click(object sender, EventArgs e)
        {
            try
            {
                mf.timer2.Enabled = false;
                mf.recBuffer.Clear();
                MainForm.isSuccess = false;
                mf.SendCmd(Protocol.GetWriteDeviceCmd(0x0A,new byte[1] { Convert.ToByte(dIndex) }));
                Thread sub = new Thread(() =>
                {
                    if (mf.CheckReturnCmd())
                    {
                        dgvYc.Invoke((MethodInvoker)delegate
                        {
                            dgvYc.Rows.Clear();
                            dgvYc.Rows.Add(43);
                            for (int i = 0; i < mf.flowData.Length; i++)
                            {
                                dgvYc.Rows[i % 43].Cells[(i / 43) * 2].Value = i;
                                dgvYc.Rows[i % 43].Cells[(i / 43) * 2 + 1].Value = mf.flowData[i] / 100000.0;
                            }
                            Messages.ShowAlertDialog("读取流量堰槽设置读取成功！", true);
                        });
                    }
                    else
                    {
                        Messages.ShowAlertDialog("读取流量堰槽设置读取失败！", false);
                    }
                });
                sub.IsBackground = true;
                sub.Start();
                mf.timer2.Enabled = true;
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("读取流量堰槽设置失败！", ex);
            }
        }

        /// <summary>
        /// 流量堰槽设置写入
        /// </summary>
        private void btnWriteYc_Click(object sender, EventArgs e)
        {
            try
            {
                List<byte> listData = new List<byte>();
                if (CheckFlowData(ref listData))
                {
                    MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
                    DialogResult dr = MessageBox.Show("确定要写入流量堰槽设置吗?", "流量堰槽设置", messButton);
                    if (dr == DialogResult.OK)
                    {
                        mf.timer2.Enabled = false;
                        mf.recBuffer.Clear();
                        MainForm.isSuccess = false;
                        listData.Insert(0, Convert.ToByte(dIndex));
                        mf.SendCmd(Protocol.GetWriteDeviceCmd(0x0B, listData.ToArray()));
                        Thread sub = new Thread(() =>
                        {
                            if (mf.CheckReturnCmd())
                            {
                                //Messages.ShowAlertDialog("写入流量堰槽设置成功！", true);
                            }
                            else
                            {
                                Messages.ShowAlertDialog("写入流量堰槽设置超时！", false);
                            }
                        });
                        sub.IsBackground = true;
                        sub.Start();
                        mf.timer2.Enabled = true;
                    }
                }
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("写入流量堰槽设置失败！", ex);
            }
        }

        /// <summary>
        /// 流量堰槽设置从Excel加载
        /// </summary>
        private void btnExcelLoad_Click(object sender, EventArgs e)
        {
            try
            {
                openFileDialog.DefaultExt = "*.xls";
                openFileDialog.Filter = "excel 2003(*.xls)|*.xls|excel 2007(*.xlsx)|*.xlsx";
                openFileDialog.RestoreDirectory = true;
                openFileDialog.FileName = "堰槽数据表.xls";
                openFileDialog.FilterIndex = 1;
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    DataTable dtExcel = ExcelManage.ExcelToDataTable(openFileDialog.FileName, false);
                    //dtExcel = Common.Transtorm(dtExcel);
                    //导入前检核
                    if (dtExcel.Rows.Count > 0)
                    {
                        if (dtExcel.Rows.Count != 256)
                        {
                            Messages.ShowAlertDialog("从Excel加载的数据个数不等于256！", false);
                            return;
                        }

                        if (dtExcel.Columns.Count == 0)
                        {
                            Messages.ShowAlertDialog("从Excel加载的数据格式错误！", false);
                            return;
                        }
                    }

                    dgvYc.Rows.Clear();
                    dgvYc.Rows.Add(43);
                    for (int i = 0; i < 256; i++)
                    {
                        dgvYc.Rows[i % 43].Cells[(i / 43) * 2 + 0].Value = i;
                        dgvYc.Rows[i % 43].Cells[(i / 43) * 2 + 1].Value = Convert.ToDouble(dtExcel.Rows[i][0].ToString());
                    }
                    Messages.ShowAlertDialog("从Excel加载成功！", true);
                }
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("从Excel加载失败！", ex);
            }
        }

        /// <summary>
        /// 流量堰槽设置导出Excel
        /// </summary>
        private void btnImportExcel_Click(object sender, EventArgs e)
        {
            try
            {
                List<byte> listData = new List<byte>();
                if (CheckFlowData(ref listData))
                {
                    FolderBrowserDialog fbd = new FolderBrowserDialog();
                    fbd.SelectedPath = @"C:\";
                    if (fbd.ShowDialog() == DialogResult.OK)
                    {
                        if (fbd.SelectedPath != string.Empty)
                        {
                            double[] data = GetFlowData(listData.ToArray());
                            string strFullFileName = fbd.SelectedPath + "\\" + "堰槽数据表.xls";
                            DataTable dtNew = new DataTable();
                            dtNew.Columns.Add("截面积");
                            for (int i = 0; i < data.Length; i++)
                            {
                                dtNew.Rows.Add(new object[] { data[i] });
                            }
                            //ExcelManage.TableToExcelForXLSX(dtNew, strFullFileName, "堰槽截面积");
                            ExcelManage.TableToExcelForXLS(dtNew, strFullFileName);
                            Messages.ShowAlertDialog("导出Excel成功！", true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("导出Excel失败！", ex);
            }
        }

        /// <summary>
        /// 流量堰槽设置查看堰槽外形等效示意图
        /// </summary>
        private void btnYcImage_Click(object sender, EventArgs e)
        {
            try
            {
                List<byte> listData = new List<byte>();
                if (CheckFlowData(ref listData))
                {
                    WeirChannel wc = new WeirChannel(GetFlowData(listData.ToArray()));
                    wc.StartPosition = FormStartPosition.CenterParent;
                    wc.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                Messages.SaveLogDialog("查看堰槽外形等效示意图失败！", ex);
            }
        }

        private void FlowWeirGroove_FormClosing(object sender, FormClosingEventArgs e)
        {
            mf.flowWeirGroove.Dispose();
            mf.flowWeirGroove = null;
        }
    }
}
